<template>
	<scroll-view :class="pageClass" :style="pageStyle" v-if="pageReady">
		<moxi-nav :set="navSet"></moxi-nav>
		<view class="upper">
			<view style="display: flex;justify-content: space-between;align-items: center">
				<view>
					<view class="address">
						{{merchantname}}
						<u-icon name="arrow-right" size="8"></u-icon>
					</view>
					<view class="distance">
						<u-icon name="map" size="8"></u-icon>
						距离您{{juli}}Km
					</view>
				</view>
				<view>
					<view v-if="isWay" style="height: 24px;width: 60px;">
						<u-button :custom-style="{height: '100%', width: '100%'}" :color="colorList[4]"
							:text="tNum ? tNum : '自取'"></u-button>
					</view>
					<view v-else style="height: 24px;width: 60px;">
						<u-button :custom-style="{height: '100%', width: '100%'}" :color="colorList[4]"
							:text="tNum ? tNum : '外带'"></u-button>
					</view>
				</view>
			</view>
			<view class="notice" >
				<view style="color: #6B7280;width:100%;">
					<view v-if="text1.some(item => item.trim() !== '')">
						<u-notice-bar :text="text1" direction="column" ></u-notice-bar>
					</view>
					<view v-else>暂无信息</view>
				</view>
			</view>
			<view class="dinner" :style="{background:colorList[4]}">
				<view style="display: flex;gap: 8px;color: #3D3D3D;color: white;">
					<u-icon name="integral" size="14" color="white"></u-icon>
					用餐方式
				</view>
				<!-- //true ts   false  wd -->
				<view v-if="isWay" style="display: flex;color: #3D3D3D;color: white;align-items: center;">
					堂食
					<u-icon name="arrow-right" size="8" color="white"></u-icon>
				</view>
				<view v-else style="display: flex;color: #3D3D3D;color: white;align-items: center;">
					外带
					<u-icon name="arrow-right" size="8" color="white"></u-icon>
				</view>
			</view>
			<view v-if="list1.length > 0 ">
				<!-- <u--image src="https://tse2-mm.cn.bing.net/th/id/OIP-C.hD5IB8D34e8ox0nyea5XVAHaEK?rs=1&pid=ImgDetMain"
					radius="6" height="80" width="100%"></u--image> -->
					<!-- 有则展示 -->
					<u-swiper imgMode="scaleToFill" :list="list1" ></u-swiper>
			</view>
		</view>
		<view class="below">
			<view class="title-list-box">
				<view class="title-list" v-for="(shop, shopId,index) in infoData" :key="shopId"
					:class="{active: activeIndex === index}" :style="{color:activeIndex === index ? colorList[4] :''}"
					@click="handleClick(index, shopId)">
					{{shop.typeinfo.name}}
				</view>
			</view>
			<view class="content-list-box">
				<!-- <view style="height: 80px;width: 100%;">
					<image style="height: 100%;width: 100%;border-radius: 10px;"
						src="https://tse2-mm.cn.bing.net/th/id/OIP-C.ylkAicuZKTEN9gWbn4MwMQHaDt?rs=1&pid=ImgDetMain">
					</image>
				</view> -->

				<scroll-view scroll-y :style="{
					height: text1.length === 0 ? '80vh' : 
					(list1.length === 0 ? '64vh' : '48vh')
						}">
					<view style="font-size: 16px;margin-bottom: 12px;">
						<text>推荐</text>
					</view>
					<view style="display: flex;gap: 12px;flex-direction: column;padding-bottom: 140px;">
						<view style="display: flex;gap: 12px;" v-for="(dishData,_index) in currentFoodList">
							<view style="width: 80px;height: 80px;">
								<image :src="dishData.img" class="img-data-box"></image>
							</view>
							<view class="dish">
								<view style="font-size: 14px;">{{dishData.name}}</view>
								<view
									style="display: flex;justify-content: space-between;align-items: center;font-size: 14px;">
									<view :style="{color:colorList[4]}">
										￥{{dishData.price}}
									</view>
									<view>
										<view v-if="hasSpecs(dishData)" style="height: 24px;width: 82px;">
											<!-- #ifndef MP-ALIPAY || MP-BAIDU -->
											<u-button @click="specsChange(dishData)"
												:custom-style="{height: '100%', width: '100%',BorderRadius: '20px',fontSize: '14px；'}"
												:color="colorList[4]" ><text>选规格</text></u-button>
											<!-- #endif -->
											<!-- #ifdef MP-ALIPAY || MP-BAIDU -->
											<button class="alipay-specs-btn" @tap="handleAlipaySpecs(dishData)"
												:style="{ background: colorList[4] }">选规格</button>
											<!-- #endif -->
										</view>
										<view v-else style="height: 24px;width: 24px;">
											<u-button
												:custom-style="{height: '100%', width: '100%',BorderRadius: '50%'}"
												:color="colorList[4]" @click="addItem(dishData)">
												<u-icon size="10" name="plus" color="white"></u-icon>
											</u-button>
										</view>
									</view>
								</view>
							</view>
							<view >
								<!-- #ifdef MP-ALIPAY || MP-BAIDU  -->
								<view v-if="show"  class="alipay-popup-mask" @tap="handleAlipayPopup('close')">
									<view class="alipay-popup-content" @tap.stop>
										<view class="popup-close-btn" @tap="handleAlipayPopup('close')">×</view>
										<view v-if="popupType === 'specs' && currentDish" class="checkbox-buttons">
											<view style="display: flex;gap: 10px;">
												<view style="width: 80px;height: 80px;">
													<image :src="currentDish.img" class="img-data-box"></image>
												</view>
												<view class="set-meal">
													<view>{{currentDish.name}}</view>
													<view style="font-size: 10px;color: #999999;">
														规格：{{currentDish.name}}
													</view>
													<view>￥{{currentDish.price}}</view>
												</view>
												<view class="dish-sum">x{{dishCount}}</view>
											</view>
											<view v-for="(specGroup, groupIndex) in specsDataList">
												<view>{{specGroup.name}}</view>
												<view style="display: flex;gap:12px;flex-wrap: wrap;margin-top: 12px;">
													<!-- #ifndef MP-ALIPAY || MP-BAIDU -->
													<view v-for="(item, itemIndex) in specGroup.list"
														class="checkbox-button"
														:class="{ active: isSpecSelected(groupIndex, itemIndex) }"
														@click="selectSpecItem(groupIndex, itemIndex)">
														{{ item.name }}
													</view>
													<!-- #endif -->
													<!-- #ifdef MP-ALIPAY || MP-BAIDU -->
													<view v-for="(item, itemIndex) in specGroup.list"
														class="checkbox-button"
														:class="{ active: isSpecSelected(groupIndex, itemIndex) }"
														@click="selectSpecItem(groupIndex, itemIndex)"
														:style="isSpecSelected(groupIndex, itemIndex) ? 'background-color: ' + colorList[4] + '; border-color: ' + colorList[4] + ';color:white;' : ''">
														{{ item.name }} 
													</view>
													<!-- #endif -->
												</view>
											</view>
											<view style="display: flex;justify-content: space-between;">
												<text>数量</text>
												<view style="display: flex;gap: 10px;">
													<view style="height: 24px;width: 24px;">
														<u-button
															:custom-style="{height: '100%', width: '100%',BorderRadius: '20px'}"
															plain :color="colorList[4]" @click="reduceDishCount">
															<u-icon size="10" name="minus"
																:color="colorList[4]"></u-icon>
														</u-button>
													</view>
													{{dishCount}}
													<view style="height: 24px;width: 24px;">
														<u-button
															:custom-style="{height: '100%', width: '100%',BorderRadius: '20px'}"
															:color="colorList[4]" @click="addDishCount()">
															<u-icon size="10" name="plus" color="white"></u-icon>
														</u-button>
													</view>

												</view>
											</view>
											<view style="display: flex;justify-content: space-between;">
												<text>总计：</text>
												<view style="display: flex;" :style="{color:colorList[4]}">
													<view>
														<text>￥</text>
													</view>
													<view style="font-size: 18px;">
														<text>{{totalCasual}}</text>
													</view>
												</view>
											</view>
											<view
												style="margin-top: 20px;display: flex;justify-content: space-between;gap: 12px;">
												<view style="width: 100%;height: 100%;">
													<u-button plain :custom-style="{BorderRadius: '20px'}"
														:color="colorList[4]" @click="addToCart">加入购物车</u-button>
												</view>
												<view style="width: 100%;height: 100%;">
													<u-button :custom-style="{BorderRadius: '20px'}"
														:color="colorList[4]" @click="buyNow">立即购买</u-button>
												</view>
											</view>
										</view>
										<!-- 打开购物车 -->
										<view v-if="popupType === 'cart'">
											<view class="select-all-bar2">
												<!-- #ifndef MP-ALIPAY -->
												<u-checkbox-group @change="selectAllChange"
													:value="isSelectAll ? [true] : []">
													<u-checkbox v-model="isSelectAll" :name="true"
														shape="circle"></u-checkbox>
													<text
														style="display: flex;align-items: center;font-size: 10px;">全选</text>
												</u-checkbox-group>
												<!-- #endif -->
												<!-- #ifdef MP-ALIPAY -->
												<view @tap="toggleSelectAll" class="alipay-checkbox">
													<view class="checkbox-icon" :class="{ 'checked': isSelectAll }">
														<u-icon v-if="isSelectAll" name="checkbox-mark" color="#ffffff"
															size="12"></u-icon>
													</view>
													<text class="select-all-text">全选</text>
												</view>
												<!-- #endif -->
											</view>
											<view
												style="height: 60vh;margin: 12px 12px 12px 16px;;display: flex;flex-direction: column;gap: 12px;">
												<scroll-view scroll-y>
													<view style="display: flex;gap: 10px;flex-direction: column;">
														<view v-for="(item, index) in cartItems" :key="index"
															style="display: flex;gap: 12px;">
															<view class="checkbox-css">
																<!-- #ifndef MP-ALIPAY -->
																<u-checkbox-group
																	@change="val => itemSelectChange(val, index)"
																	:value="item.selected ? [item.id] : []">
																	<u-checkbox v-model="item.selected" :name="item.id"
																		shape="circle"></u-checkbox>
																</u-checkbox-group>
																<!-- #endif -->
																<!-- #ifdef MP-ALIPAY || MP-TOUTIAO -->
																<view @tap="() => toggleItemSelect(index)"
																	class="alipay-checkbox">
																	<view class="checkbox-icon"
																		:class="{ 'checked': item.selected }">
																		<u-icon v-if="item.selected"
																			name="checkbox-mark" color="#ffffff"
																			size="12"></u-icon>
																	</view>
																</view>
																<!-- #endif -->
															</view>
															<view style="width: 80px; height: 80px;">
																<image :src="item.img" class="img-data-box"></image>
															</view>
															<view class="set-meal">
																<view>{{item.name}}</view>
																<view style="font-size: 10px;color: #999999;">
																	规格：{{ item.specs.map(s => s.name).join(' / ') }}
																</view>
																<view>￥{{item.totalPrice.toFixed(2)}}</view>
															</view>
															<view class="dish-sum">
																<view
																	style="display: flex;gap: 4px;align-items: center;">
																	<view
																		style="display: flex;width: 80px;gap: 8px;align-items: center;">
																		<view style="width: 24px; height: 24px;">
																			<u-button
																				:custom-style="{height: '100%', width: '100%',borderRadius: '20px'}"
																				plain :color="colorList[4]"
																				@click="reduceCartItem(index)">
																				<u-icon size="10" name="minus"
																					:color="colorList[4]"></u-icon>
																			</u-button>
																		</view>
																		{{item.count}}
																		<view style="width: 24px; height: 24px;">
																			<u-button
																				:custom-style="{height: '100%', width: '100%',borderRadius: '20px'}"
																				:color="colorList[4]"
																				@click="addCartItem(index)">
																				<u-icon size="10" name="plus"
																					color="white"></u-icon>
																			</u-button>
																		</view>
																	</view>
																</view>
															</view>
														</view>

													</view>
													<view v-if="cartItems.length === 0"
														style="text-align: center;padding: 50rpx;display: flex;justify-content: center;height: 100%;">
														<u-empty mode="car" text="当前购物车空空如也~"></u-empty>
													</view>
												</scroll-view>
											</view>
											<view class="settlement" style="bottom: -50px;">
												<view style="flex: 1;">
													<view style="display: flex;align-items: center;">
														<u-tag bgColor="rgb(0 0 0 / 0%)" borderColor="rgb(0 0 0 / 0%)"
															icon="shopping-cart" size="large"></u-tag>
														<view style="position:absolute;left: 28px;top: 8px;">
															<u-badge :bgColor="colorList[4]" numberType="overflow"
																max="99" :value="shoppingValue"></u-badge>
														</view>
														合计：
														<span style="font-size: 18px;" :style="{color:colorList[4]}">
															￥{{(selectedTotalPrice || 0).toFixed(2)}}</span>
													</view>
												</view>
												<view class="settlement-button" :style="'background: '+colorList[4]"
													@click="settlementClick">
													结算
												</view>
											</view>
										</view>

									</view>
								</view>
								<!-- #endif -->

								
							</view>
						</view>
					</view>
					
				</scroll-view>
				
				<!-- #ifndef MP-ALIPAY || MP-BAIDU -->
				<u-popup  :closeable="true"   :show="show" @close="close" mode="bottom" :round="10">
					<view v-if="popupType === 'specs' && currentDish" style="display: flex;gap: 10px;margin-left: 10px;margin-top: 10px;">
						<view style="width: 80px;height: 80px;">
							<image :src="currentDish.img" class="img-data-box"></image>
						</view>
						<view class="set-meal">
							<view>{{currentDish.name}}</view>
							<view style="font-size: 10px;color: #999999;">规格：{{currentDish.name}}
							</view>
							<view>￥{{currentDish.price}}</view>
						</view>
						<view class="dish-sum" style="margin-right: 10px;">x{{dishCount}}</view>
					</view>
					<scroll-view scroll-y :style="{maxHeight: '48vh'}">
					<view v-if="popupType === 'specs' && currentDish" class="checkbox-buttons" style="margin-bottom: 30px;position: relative;">
						
						<view v-for="(specGroup, groupIndex) in specsDataList">
							
							<view>{{specGroup.name}}</view>
							<view style="display: flex;gap:12px;flex-wrap: wrap;margin-top: 12px;">
								<view v-for="(item, itemIndex) in specGroup.list"
									class="checkbox-button"
									:class="{ active: isSpecSelected(groupIndex, itemIndex) }"
									@click="selectSpecItem(groupIndex, itemIndex)"
									:style="isSpecSelected(groupIndex, itemIndex) ? 'background-color: ' + colorList[4] + '; border-color: ' + colorList[4] + ';color:white;' : ''">
									{{ item.name }}
								</view>
							</view>
						</view>
						
					</view>
					<view v-if="popupType === 'cart'" >
						<view class="select-all-bar" >
							<u-checkbox-group @change="selectAllChange"
								:value="isSelectAll ? [true] : []">
								<u-checkbox v-model="isSelectAll" :name="true"
									shape="circle"></u-checkbox>
								<text
									style="display: flex;align-items: center;font-size: 10px;">全选</text>
							</u-checkbox-group>
						</view>
						<view
							style="margin: 12px 12px 12px 16px;display: flex;gap: 12px;">
							<scroll-view scroll-y >
								<view style="display: flex;gap: 10px;flex-direction: column;">
									<view v-for="(item, index) in cartItems" :key="index"
										style="display: flex;gap: 12px;">
										<view style="display: flex;align-items: center;">
											<u-checkbox-group
												@change="val => itemSelectChange(val, index)"
												:value="item.selected ? [item.id] : []">
												<u-checkbox v-model="item.selected" :name="item.id"
													shape="circle"></u-checkbox>
											</u-checkbox-group>
										</view>
										<view style="width: 80px; height: 80px;">
											<image :src="item.img" class="img-data-box"></image>
										</view>
										<view class="set-meal">
											<view>{{item.name}}</view>
											<view style="font-size: 10px;color: #999999;">
												规格：{{ item.specs.map(s => s.name).join(' / ') }}
											</view>
											<view>￥{{item.totalPrice.toFixed(2)}}</view>
										</view>
										<view class="dish-sum">
											<view style="display: flex;gap: 4px;align-items: center;">
												<view
													style="display: flex;width: 80px;gap: 8px;align-items: center;">
													<view style="width: 24px; height: 24px;">
														<u-button
															:custom-style="{height: '100%', width: '100%',borderRadius: '20px'}"
															plain :color="colorList[4]"
															@click="reduceCartItem(index)">
															<u-icon size="10" name="minus"
																:color="colorList[4]"></u-icon>
														</u-button>
													</view>
													{{item.count}}
													
													<view style="width: 24px; height: 24px;">
														<u-button
															:custom-style="{height: '100%', width: '100%',borderRadius: '20px'}"
															:color="colorList[4]"
															@click="addCartItem(index)">
															<u-icon size="10" name="plus"
																color="white"></u-icon>
														</u-button>
													</view>
												</view>
											</view>
										</view>
									</view>
									
								</view>
								<view v-if="cartItems.length === 0"
									style="text-align: center;padding: 50rpx;display: flex;justify-content: center;height: 100%;">
									<u-empty mode="car" text="当前购物车空空如也~"></u-empty>
								</view>
							</scroll-view>
						</view>
						
					</view>
					</scroll-view>
					<view style="margin:10px 10px 10px 10px;" v-if="popupType === 'specs' && currentDish">
						<!-- 数量 -->
						<view style="display: flex;justify-content: space-between;">
							<text>数量</text>
							<view style="display: flex;gap: 10px;">
								<view style="height: 24px;width: 24px;">
									<u-button
										:custom-style="{height: '100%', width: '100%',BorderRadius: '20px'}"
										plain :color="colorList[4]" @click="reduceDishCount">
										<u-icon size="10" name="minus" :color="colorList[4]"></u-icon>
									</u-button>
								</view>
								{{dishCount}}
								<view  style="height: 24px;width: 24px;">
									<u-button
										:custom-style="{height: '100%', width: '100%',BorderRadius: '20px'}"
										:color="colorList[4]" @click="addDishCount()">
										<u-icon size="10" name="plus" color="white"></u-icon>
									</u-button>
								</view>
										
							</view>
						</view>
						<!-- 总计 -->
						<view style="display: flex;justify-content: space-between;margin-top: 10px;">
							<text>总计：</text>
							<view style="display: flex;" :style="{color:colorList[4]}">
								<view>￥</view>
								<view style="font-size: 18px;margin-right: 20px;">
									{{totalCasual}}
								</view>
							</view>
						</view>
						<view
							style="margin-top: 20px;display: flex;justify-content: space-between;gap: 12px;">
							<view style="width: 100%;height: 100%;">
								<u-button plain :custom-style="{BorderRadius: '20px'}"
									:color="colorList[4]" @click="addToCart">加入购物车</u-button>
							</view>
							<view style="width: 100%;height: 100%;">
								<u-button :custom-style="{BorderRadius: '20px'}" :color="colorList[4]"
									@click="buyNow">立即购买</u-button>
							</view>
						</view>
					</view>
				</u-popup>
				<!-- #endif -->
			</view>
		</view>

		<view class="settlement" >
			<view style="flex: 1;">
				<view style="display: flex;align-items: center;">
					<view>
						<u-tag bgColor="rgb(0 0 0 / 0%)" borderColor="rgb(0 0 0 / 0%)" icon="shopping-cart" size="large"
							@click="showCartPopup"></u-tag>
					</view>
					<view style="position:absolute;left: 28px;top: 8px;">
						<u-badge :bgColor="colorList[4]" numberType="overflow" max="99"
							:value="shoppingValue"></u-badge>
					</view>
					<text>合计：</text>
					<span style="font-size: 18px;" :style="{color: colorList[4]}">
						<text style="font-size: 10px;">￥</text>{{(selectedTotalPrice || 0).toFixed(2)}}</span>
				</view>
			</view>
			<view class="settlement-button" :style="{background:colorList[4]}" @click="settlementClick">
				结算
			</view>
		</view>

		<moxi-tabbar :set="tabbar" v-if="tabbar.index_id"></moxi-tabbar>
	</scroll-view>
</template>

<script>
	export default {
		data() {
			return {
				mid: 0,//默认为0
				selectedSpecs: [], // 用于存储用户选择的规格
				specsDataList: [], // 存储规格数据
				show: false,
				isWay: true,
				tNum:'',
				isZH:false,
				showShoping: true,
				dishCount: 1,
				popupType: '', // 'specs'或'cart'，表示当前弹窗类型
				currentDish: null,
				activeShopId: null, // 当前选中的分类ID
				infoData: {}, // 原始数据
				activeIndex: 0, // 当前选中分类索引
				shoppingValue: 0, // 购物车商品总数
				totalCasual: 0, // 选规格的总计
				totalPrice: 0, // 购物车的总金额
				cartItems: [], //本地存储购物数据
				selectedItems: [], // 选中的商品ID数组
				isSelectAll: false, //是否全选
				text1: [],
				text2:['这是第一条消息', '这是第二条消息'],
				merchantname:'',
				list1:[], //轮播图
				tid:0,//桌号id
				merchantInfo:[],
				juli:'',
				instance:0,
				pclocation:{
					lat:0,
					lng:0
				},
				location:{
					lat:0,
					lng:0
				},
				merchantlocation:{
					lat:0,
					lng:0
				},
				dishList: [{
						id: 1,
						img: 'https://bpic.588ku.com/back_origin_min_pic/21/03/30/f7f0ac6353dc95a90eafb8975667c840.jpg',
						title: '辣椒炒肉',
						price: 12.99,
						specs: '米饭+辣椒炒肉',
						count: 0
					},
					{
						id: 2,
						img: 'https://ts1.tc.mm.bing.net/th/id/R-C.14337274710a026a3bab66a788784f53?rik=Zlfhh9vxQdsI2Q&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f50075%2f0465.jpg_wh1200.jpg&ehk=mhv8TEKhG6hBEQ%2bkjlnKPXih%2ftzpMcaMFXDhyKyU7Rk%3d&risl=&pid=ImgRaw&r=0',
						title: '肥牛炒肉',
						specs: '米饭+肥牛炒肉',
						price: 15.99,
						count: 0
					}
				],

			}
		},
		onLoad(option) {
			console.log(this.colorList);
			//这里做扫二维码传参准备
			if(typeof option.tid!== 'undefined'){
				//有桌号，自取堂食
				this.isWay = true;
				this.tid = option.tid
				console.log('asdfasdfasd:',option.tid);
				this.getTable(option.tid,this.param.mid);
			}else{
				//没桌号
				//外带打包
				this.isWay = false;
			}
			// console.log(this.isWay);
			
			this.mid = this.param.mid;
			if (this.param.mid) {
				//获取商家信息，拿到轮播图
				this.getMerchantInfo(this.param.mid)
			}
			//页面加载时触发
			this.juli = option.instance
			this.get(this.param.mid);
			this.getName(this.param.mid)
			this.getImg(this.param.mid)
			//清空购物车
			this.emptyCart();
			this.loadCart();
		},
		onShow() {
			//页面显示时触发
			this.loadCart();
		},
		// #ifdef MP-ALIPAY || MP-BAIDU 
		// 在onReady中添加支付宝弹窗优化
		onReady() {
			if (typeof my !== 'undefined') {
				this.popup = this.selectComponent('#specs-popup');
			}
		},
		// 页面卸载时清理
		onUnload() {
			// this.currentDish = null;
			// this.specsDataList = [];
			if (this.popupTimer) clearTimeout(this.popupTimer);
			this.popupAnim = null;
		},
		// #endif

		computed: {
			// 计算选中的总价
			selectedTotalPrice() {
				return this.cartItems
					.filter(item => item.selected)
					.reduce((sum, item) => sum + (Number(item.totalPrice) || 0), 0);
			},
			// 计算选中商品数量
			selectedCount() {
				return this.cartItems
					.filter(item => item.selected)
					.reduce((count, item) => count + (item.count || 0), 0);
			},
			// 当前分类的菜品列表
			currentFoodList() {
				if (!this.activeShopId) return [];
				const shop = this.infoData[this.activeShopId];
				const foodList = shop?.foodlist || [];
				return foodList.map(food => {
					const cartItem = this.cartItems?.find(item => item.id === food.id);
					return {
						...food,
						count: cartItem?.count || 0
					};
				});
			},
		},
		methods: {
			
			getImg(mid){
				//获取轮播图
				this.moxiPost('/plugin/order/user/user/getimg',{'mid':mid},(res)=>{
					res.data.img_list.forEach((item)=>{
						this.list1.push(item)
					})
				})
			},
			//桌号信息
			getTable(tid,mid){
					this.isZH = true;
					this.moxiPost('/plugin/order/user/user/gettable',{'mid':mid,'tid':tid},(res)=>{
							this.tNum = res.data.name		
					})
			},
			//商家信息
			getMerchantInfo(mid){
				this.moxiPost('/plugin/order/index/merchant/getaddress',{'mid':mid},
				(res)=>{
					this.merchantInfo = res.data;
						//处理单层嵌套数组
						this.merchantInfo.notice = this.merchantInfo.notice.split(",")
						// console.log(this.merchantInfo.notice);
						// console.log(111);
					if(this.merchantInfo.notice.length > 0){
						this.merchantInfo.notice.forEach((item)=>
						{
							const processedItem = item.replace(/[\[\]"]/g, '');
							this.text1.push(processedItem)
							});
					}
					
					})
			},
			
			//获取信息
			get(mid) {
				// uni.removeStorageSync('cart');
				this.moxiPost("/plugin/order/index/merchant/gettypeandfood", {'mid':mid}, (res) => {
					// console.log("获取的信息：", res);
					console.log("获取的data：", res.data);
					// return false;
					const rawData = JSON.parse(JSON.stringify(res.data));
					// 初始化数据结构
					Object.keys(rawData).forEach(shopId => {
						const shop = rawData[shopId];
						if (shop.foodlist) {
							shop.foodlist.forEach(food => {
								// 初始化数量
								this.$set(food, 'count', 0);
							});
						}
					});
					// 响应式更新数据
					this.$set(this, 'infoData', rawData);
					// 设置默认选中的第一个
					const firstShopId = Object.keys(rawData)[0];
					if (firstShopId) {
						this.activeShopId = firstShopId;
						this.activeIndex = 0;
					}
					console.log("初始化完成:", {
						infoData: this.infoData,
						activeShopId: this.activeShopId,
						currentFoodList: this.currentFoodList
					});
				})
			},
			getName(mid){
				this.moxiPost(
				'/plugin/order/index/merchant/getName',{'mid':mid},(res)=>{this.merchantname = res.data.name}
				)
			},
			// #ifdef MP-ALIPAY || MP-BAIDU 
			handleAlipaySpecs(dishData) {
				console.log("支付宝的dishdata:", dishData);
				let specs = [];
				try {
					specs = JSON.parse(dishData.specs || '[]');
				} catch (e) {
					uni.showToast({
						title: '规格数据错误',
						icon: 'none'
					});
					return;
				}
				if (!specs.length) {
					uni.showToast({
						title: '该菜品暂无规格可选',
						icon: 'none'
					});
					return;
				}
				this.currentDish = {
					id: dishData.id,
					name: dishData.name,
					price: dishData.price,
					img: dishData.img,
					count: 1
				};
				this.$nextTick(() => {
					this.dishCount = 1;
					this.specsDataList = specs;
					this.selectedSpecs = new Array(specs.length).fill(0);
					setTimeout(() => {
						this.popupType = 'specs';
						this.show = true;
						this.calculatePrice('casual');
					}, 50);
				});
			},
			// #endif
			// 判断是否有规格
			hasSpecs(dishData) {
				try {
					const specs = JSON.parse(dishData.specs || '[]');
					return specs.length > 0;
				} catch {
					return false;
				}
			},
			//点击分类
			handleClick(index, shopId) {
				this.activeIndex = index;
				this.activeShopId = shopId;
				console.log("切换到:", {
					index,
					shopId,
					foodlist: this.infoData[shopId]?.foodlist
				});
				console.log("点击第:", index, "个");
				console.log("shopId:", shopId);
			},
			//全选
			selectAllChange(val) {
				this.isSelectAll = val.includes(true);
				this.cartItems.forEach(item => {
					item.selected = this.isSelectAll;
				});
				// this.updateSelectedStatus();
				this.saveCartData();
				console.log("全选：", val);
			},
			//单选
			itemSelectChange(val, index) {
				this.cartItems[index].selected = val.length > 0;
				this.updateSelectedStatus();
				this.saveCartData();
			},
			// #ifdef MP-ALIPAY || MP-BAIDU 
			toggleSelectAll() {
				this.isSelectAll = !this.isSelectAll;
				this.cartItems.forEach(item => {
					item.selected = this.isSelectAll;
				});
				this.saveCartData();
				console.log("全选状态：", this.isSelectAll);
			},
			// #endif
			// 单项选择
			toggleItemSelect(index) {
				this.cartItems[index].selected = !this.cartItems[index].selected;
				this.updateSelectedStatus();
				this.saveCartData();
			},
			// 更新选中状态
			updateSelectedStatus() {
				this.selectedItems = this.cartItems
					.filter(item => item.selected)
					.map(item => item.id);
				this.isSelectAll = this.cartItems.length > 0 &&
					this.cartItems.every(item => item.selected);
			},
			// 显示规格选择弹窗
			specsChange(dishData) {
				if (!dishData.specs || !JSON.parse(dishData.specs)?.length) {
					uni.showToast({
						title: '该菜品暂无规格可选',
						icon: 'none'
					});
					return;
				}
				this.$set(dishData, 'count', 1);
				this.currentDish = {
					...dishData
				};
				this.dishCount = dishData.count || 1;
				console.log("当前选择的是：", dishData);
				this.popupType = 'specs';
				this.show = true;
				this.specsDataList = JSON.parse(dishData.specs);
				console.log("当前选择的specsDataList有：", this.specsDataList);
				this.selectedSpecs = this.specsDataList.map(() => 0);
				console.log("初始化选择数组：", this.selectedSpecs);
				this.calculatePrice('casual');

				if (typeof my !== 'undefined') {
					this.handleAlipayPopup('open');
				} else {
					this.show = true;
				}
			},
			// 统一价格计算方法 (type: 'cart'|'casual')  bug
			calculatePrice(type = 'casual') {
				if (!this.currentDish) return 0;
				// 确保价格是数值类型
				const basePrice = Number(this.currentDish.price) || 0;
				let specsTotal = 0;
				// 确保遍历所有规格组
				this.specsDataList.forEach((group, groupIdx) => {
					const selectedIdx = this.selectedSpecs[groupIdx];
					if (selectedIdx !== undefined && group.list) {
						const selectedSpec = group.list[selectedIdx];
						specsTotal += Number(selectedSpec?.price) || 0;
					}
				});
				const total = (basePrice + specsTotal) * this.dishCount;
				this.totalCasual = total.toFixed(2);
				return this.totalCasual;
			},
			// 规格选择
			selectSpecItem(groupIndex, itemIndex) {
				this.$set(this.selectedSpecs, groupIndex, itemIndex);
				this.calculatePrice('casual');
				console.log(groupIndex, itemIndex);
			},
			// 检查是否选中
			isSpecSelected(groupIndex, itemIndex) {
				return this.selectedSpecs[groupIndex] === itemIndex;
			},
			// 计算购物车商品总价
			calcItemPrice(item) {
				if (!item) return 0;
				const basePrice = Number(item.price) || 0;
				const specsPrice = item.specs.reduce((specSum, spec) => specSum + (Number(spec.price) || 0), 0);
				const itemTotal = (basePrice + specsPrice) * (item.count || 0);
				console.log("总计:", itemTotal.toFixed(2));
				return itemTotal;
			},
			//清空购物车
			emptyCart(){
				uni.removeStorageSync('cart');
			},
			// 更新购物车中的商品
			updateDishInCart(dish) {
				const index = this.cartItems.findIndex(item => item.id === dish.id);
				if (index >= 0) {
					if (dish.count > 0) {
						this.cartItems[index] = {
							...dish,
							totalPrice: this.calcItemPrice(dish)
						};
					} else {
						this.cartItems.splice(index, 1);
					}
					this.saveCartData();
				}
			},
			//选择规格后添加商品
			addItem(dishData) {
				if (!dishData || typeof dishData !== 'object') {
					console.error('Invalid dishData:', dishData);
					return;
				}
				if (!dishData.id && !dishData.price) {
					console.error('Dish data missing required fields:', dishData);
					return;
				}
				const basePrice = Number(dishData.price) || 0;
				const cartItem = {
					...dishData,
					selected: true,
					id: dishData.id || Date.now() + Math.random().toString(36).substr(2),
					specs: [],
					count: (dishData.count || 0) + 1
				};
				cartItem.totalPrice = this.calcItemPrice(cartItem);
				const existingIndex = this.cartItems.findIndex(item =>
					this.isSameItem(item, cartItem)
				);

				if (existingIndex >= 0) {
					this.$set(this.cartItems[existingIndex], 'count', this.cartItems[existingIndex].count + 1);
					this.$set(this.cartItems[existingIndex], 'totalPrice',
						basePrice * this.cartItems[existingIndex].count);
				} else {
					this.cartItems.push(cartItem);
				}
				this.saveCartData();
				uni.showToast({
					title: '已加入购物车',
					icon: 'success'
				});
				console.log('(无规格)添加的购物车项:', cartItem);
				console.log('当前购物车:', this.cartItems);
			},

			addDishCount() {
				console.log('agagaga');
				if (!this.currentDish) return;
				this.$nextTick(() => {
					this.dishCount += 1;
					this.calculatePrice('casual')
				});
				
				
			},
			reduceDishCount() {
				if (!this.currentDish || this.dishCount <= 1) return;
				this.$nextTick(() => {
					this.dishCount -= 1;
					this.calculatePrice('casual')
				});
			},
			// 商品列表增加数量
			addDish(dishData) {
				console.log("dishdata:", dishData);
				this.$set(dishData, 'count', (dishData.count || 0) + 1);
				console.log("this.cartItems:", this.cartItems);
				this.cartItems.count = dishData.count;
				this.saveCartData();
			},
			// 商品列表减少数量
			reduceDish(dishData) {
				if (dishData.count > 0) {
					this.$set(dishData, 'count', dishData.count - 1);
					this.saveCartData();
					// this.updateCartStatus();
				}
			},
			// 增加购物车商品数量
			addCartItem(index) {
				console.log('additem?????');
				this.cartItems[index].count++;
				this.cartItems[index].totalPrice = this.calcItemPrice(this.cartItems[index]);
				console.log(this.cartItems[index].totalPrice);
				this.saveCartData();
				// this.updateCartStatus();
				// this.updateSelectedStatus();
			},
			// 减少购物车商品数量
			reduceCartItem(index) {
				if (this.cartItems[index].count > 1) {
					this.cartItems[index].count--;
					this.cartItems[index].totalPrice = this.calcItemPrice(this.cartItems[index]);
				} else {
					this.cartItems.splice(index, 1);
				}
				this.saveCartData();
				// this.updateCartStatus();
				// this.updateSelectedStatus();
			},
			// 保存购物车数据
			saveCartData() {
				const newCartItems = this.cartItems.map(item => ({
					...item,
					totalPrice: this.calcItemPrice(item)
				}));
				this.cartItems = newCartItems;
				uni.setStorageSync('cart', JSON.stringify(this.cartItems));
				this.dishList = this.dishList.map(dish => {
					const cartItem = newCartItems.find(item => item.id === dish.id);
					return {
						...dish,
						count: cartItem ? cartItem.count : 0
					};
				});
				this.updateCartStatus();
				this.updateSelectedStatus();
			},
			// 更新购物车商品总数和总价
			updateCartStatus() {
				this.shoppingValue = this.cartItems.reduce((total, item) => total + (item.count || 0), 0);
				
				this.totalPrice = this.cartItems.reduce((sum, item) => {
					const basePrice = Number(item.price) || 0;
					
					const specsPrice = item.specs.reduce((specSum, spec) => specSum + (Number(spec.price) || 0),
						0);
						
					const itemTotal = ((basePrice + specsPrice) * (item.count || 0)).toFixed(2);
					console.log('当前商品总价:', itemTotal);
					var ff = sum + itemTotal;
					
					return sum + itemTotal;
				}, 0);
				this.totalPrice = Number(this.totalPrice);
				console.log('购物车总价:', this.totalPrice);
			},
			// #ifdef MP-ALIPAY || MP-BAIDU 
			handleAlipayPopup(action) {
				if (action === 'open') {
					this.$nextTick(() => {
						setTimeout(() => {
							this.show = true;
						}, 50);
					});
				} else {
					this.show = false;
					my.hideOverlay ({
						animation: false
					}); // 强制关闭支付宝原生层
				}
			},
			// #endif
			// 关闭弹窗
			close() {
				// this.show = false;
				console.log('close');
				if (typeof my !== 'undefined') {
					this.handleAlipayPopup('close');
				} else {
					this.show = false;
				}
				// 重置状态
				this.$nextTick(() => {
					this.popupType = '';
					this.currentDish = null;
				});
			},
			// 显示购物车弹窗
			showCartPopup(item) {
				this.popupType = 'cart';
				this.show = true;
				console.log("购物车被点击了");
			},
			isSameItem(item, cartItem) {
				if (!item || !cartItem) return false;
				if (item.id !== cartItem.id) return false;
				if (item.specs.length !== cartItem.specs.length) return false;
				if (item.specs.length === 0) return true;
				return cartItem.specs.every((spec, i) => {
					const targetSpec = item.specs[i];
					return targetSpec &&
						spec.groupId === targetSpec.groupId &&
						spec.name === targetSpec.name;
				});
			},
			// 加入购物车
			addToCart() {
				if (!this.currentDish) return;
				// 获取所有选中的规格组合
				const selectedSpecs = this.specsDataList.map((group, index) => {
					const selectedIdx = this.selectedSpecs[index] || 0;
					return group.list && group.list[selectedIdx] ? {
						groupId: index,
						groupName: group.name,
						...group.list[selectedIdx]
					} : null;
				}).filter(Boolean);
				// 创建购物车项
				const cartItem = {
					...this.currentDish,
					selected: true,
					id: this.currentDish.id || Date.now() + Math.random().toString(36).substr(2),
					specs: selectedSpecs.map(spec => ({
						groupId: spec.groupId,
						groupName: spec.groupName,
						name: spec.name,
						price: spec.price
					})),
					count: this.dishCount,
				};
				cartItem.totalPrice = this.calcItemPrice(cartItem);
				const existingIndex = this.cartItems.findIndex(item =>
					this.isSameItem(item, cartItem)
				);
				if (existingIndex >= 0) {
					this.cartItems[existingIndex].count += cartItem.count;
					this.cartItems[existingIndex].totalPrice = this.calcItemPrice(this.cartItems[existingIndex]);
				} else {
					this.cartItems.push(cartItem);
				}
				this.updateCartStatus();
				this.dishList.count = this.dishCount;
				this.saveCartData();
				uni.showToast({
					title: '已加入购物车',
					icon: 'success'
				});
				this.close();
				console.log('添加的购物车项:', cartItem);
				console.log('当前购物车:', this.cartItems);
			},
			// 立即购买
			buyNow() {
				this.addToCart();
				this.settlementClick()
			},
			// 加载购物车数据从本地存储读取购物车数据
			loadCart() {
				const cartData = uni.getStorageSync('cart');
				if (cartData) {
					this.cartItems = JSON.parse(cartData).map(item => ({
						...item,
						selected: item.selected !== false
					}));
					this.updateCartStatus();
					this.updateSelectedStatus();
				}
			},
			settlementClick() {
				if (this.selectedCount === 0) {
					uni.showToast({
						title: '请选择要结算的商品',
						icon: 'none'
					});
					return;
				}
				const selectedGoods = this.cartItems.filter(item => item.selected);
				uni.setStorageSync('plugin_order_selectedGoods',JSON.stringify(selectedGoods))
				// 跳转到结算页面
				
				uni.navigateTo({
					url: '/plugin_order/orderconfirm?mid='+this.mid +'&tid=' + this.tid
				});
				//清空购物车
				this.emptyCart();
			}

		}
	}
</script>

<style lang="scss" scoped>
	.active {
		background: white;
	}

	.upper {
		margin: 8px 12px 12px;
		display: flex;
		gap: 12px;
		flex-direction: column;
	}

	.upper .address {
		margin-bottom: 2px;
		font-size: 16px;
		font-weight: 500;
		line-height: normal;
		letter-spacing: normal;
		display: flex;
		align-items: center;
	}

	.upper .distance {
		display: flex;
		font-size: 12px;
		gap: 2px;
		font-weight: normal;
		line-height: normal;
		letter-spacing: normal;
		color: #6B7280;
		align-items: center;
		align-items: baseline;
	}

	.upper .dinner {
		padding: 9px 12px;
		border-radius: 6px;
		font-size: 12px;
		font-weight: normal;
		line-height: normal;
		letter-spacing: normal;
		display: flex;
		justify-content: space-between;
	}

	.upper .notice {
		font-size: 12px;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.upper .notice .notice-content {
		width: 16px;
		height: 16px;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.below {
		display: flex;
		height: 100%;
	}

	.below .title-list-box {
		background: #F5F5F5;
		width: 100px;
		display: flex;
		gap: 8px;
		flex-direction: column;
		color: #4B5563;
	}

	.below .title-list-box .title-list {
		text-align: center;
		padding: 8px 22px;
		font-size: 14px;
		cursor: pointer;
		transition: color 0.3s;
	}

	.below .content-list-box {
		display: flex;
		flex: 1;
		margin: 0 12px;
		gap: 12px;
		flex-direction: column;
	}

	.below .content-list-box .dish {
		display: flex;
		flex-direction: column;
		flex: 1;
		justify-content: space-between;
		margin: 8px 0;
	}

	.below .content-list-box .set-meal {
		display: flex;
		flex: 1;
		flex-direction: column;
		font-size: 14px;
		justify-content: space-evenly;
	}

	.below .content-list-box .dish-sum {
		font-size: 10px;
		color: #999999;
		display: flex;
		align-items: flex-end;
	}

	.below .content-list-box .dish .specs-add {
		display: flex;
		align-items: center;
		gap: 4px;
		font-size: 10px;
	}

	.settlement {
		// width: 100%;
		margin: 0px 10px;
		height: 48px;
		color: white;
		position: sticky;
		bottom: 10px;
		background: #000000;
		border-radius: 30px;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.settlement .settlement-button {
		width: 100px;
		height: 48px;
		display: flex;
		align-items: center;
		justify-content: center;
		border-top-right-radius: 30px;
		border-bottom-right-radius: 30px;
		cursor: pointer;
	}

	.checkbox-buttons {
		height: 60%;
		margin: 40px 12px 12px;
		display: flex;
		flex-direction: column;
		gap: 12px;
	}

	.checkbox-button {
		padding: 8px 24px;
		border: 1px solid #dcdfe6;
		border-radius: 4px;
		background-color: #ffffff;
		color: #606266;
		font-size: 12px;
		cursor: pointer;
		transition: all 0.3s;
	}

	.content-list-box .select-all-bar {
		width: 80px;
		display: flex;
		height: 48px;
		flex-direction: row;
		justify-content: center;

		/* #ifdef MP-TOUTIAO */
		align-items: center;
		/* #endif */

	}

	.content-list-box .select-all-bar2 {
		width: 70px;
		display: flex;
		height: 48px;
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}

	.selected-info {
		margin-top: 20px;
		font-size: 12px;
		color: #909399;
	}

	.img-data-box {
		width: 100%;
		height: 100%;
		border-radius: 10px;
	}

	.checkbox-css {
		display: flex;
	}

	/* #ifdef MP-ALIPAY || MP-BAIDU */
	/* 支付宝按钮样式 - 匹配H5的u-button效果 */
	.alipay-specs-btn {
		width: 100%;
		height: 100%;
		border-radius: 20px;
		font-size: 10px !important;
		line-height: 18px;
		padding: 0;
		margin: 0;
		color: #FFFFFF;
		box-sizing: border-box;
		position: relative;
		transition: all 0.3s;
	}

	/* 移除支付宝按钮默认样式 */
	.alipay-specs-btn::after {
		border: none;
	}

	.alipay-specs-btn:active {
		opacity: 0.7;
		transform: scale(0.98);
	}

	/* 支付宝弹窗样式 */
	.alipay-popup-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		margin-bottom: 40px;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 999;
	}

	.alipay-popup-content {
		position: absolute;
		bottom: 0;
		width: 100%;
		background: #fff;
		border-radius: 10px 10px 0 0;
		padding: 10px;
		box-sizing: border-box;
	}

	.popup-close-btn {
		position: absolute;
		right: 15px;
		top: 15px;
		font-size: 24px;
		color: #999;
	}

	/* 支付宝复选框样式 */
	.alipay-checkbox {
		display: flex;
		align-items: center;
	}

	.checkbox-icon {
		width: 18px;
		height: 18px;
		border-radius: 50%;
		border: 1px solid #ddd;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 5px;
		transition: all 0.2s;
	}

	.checkbox-icon.checked {
		background-color: #4a90e2;
		border-color: #4a90e2;
	}

	.select-all-text {
		display: flex;
		align-items: center;
		font-size: 10px;
		margin-left: 5px;
	}

	.select-all-container {
		display: flex;
		align-items: center;
	}

	/* #endif */
</style>